import torch
import json
import jieba
from model.model_BiLSTM import BiLSTM

import time
max_length=20
class Sentiment:
    def __init__(self):
        # self.max_len=max_len
        pass
    def get_stopword(self):
        with open('stopwords.txt', 'r', encoding='utf-8') as f:
            stop_words = [word.strip() for word in f]
        return stop_words

    # @staticmethod
    def sentence_2_indx(self,sentence, word_2_idx, max_length):
        stopwords = self.get_stopword()
        token = jieba.cut(sentence)
        token_words = [word for word in token if word not in stopwords]
        token_idx = []
        token_length = len(token_words)
        if token_length >= max_length:
            for word in token_words[:max_length]:
                if word in word_2_idx:
                    token_idx.append(word_2_idx[word])
                else:
                    token_idx.append(1)
        else:
            for word in token_words:
                if word in word_2_idx:
                    token_idx.append(word_2_idx[word])
                else:
                    token_idx.append(1)
            token_idx = token_idx + [0] * (max_length - token_length)
        return token_idx

    # @staticmethod
    def get_sentiment(self,inputstr):
        with open('word_2_idx_two_label.json', 'r', encoding='utf-8')as file:
            word_2_idx = json.load(file)
        word_length = len(word_2_idx)
        rnn = torch.load('emotional_analysis_two_label.pkl', map_location=lambda storage, loc: storage)
        # rnn = BiLSTM(word_length)
        # rnn.load_state_dict(torch.load('emotional_analysis.pkl'))
        token_idx = self.sentence_2_indx(inputstr, word_2_idx, max_length)
        token_idx = torch.LongTensor(token_idx)
        output = rnn(token_idx)
        output=output.data.numpy()
        print(output)
        # sentiment={}
        # sentiment['负向情感']=str(output[0])
        # sentiment['中性情感'] = str(output[1])
        # sentiment['正向情感'] = str(output[2])
        # sentiment='负向情感:{0}\n中性情感:{1}\n正向情感:{2}'.\
        #     format(str(output[0]),str(output[1]),str(output[2]))
        sentiment = '负向情感:{0}\n正向情感:{1}'. \
                format(str(output[0]),str(output[1]))
        sentiment=sentiment.split('\n')
        return sentiment



if __name__ == '__main__':
#     main()
    S=Sentiment()
    print(S.get_sentiment('这个东西很好吃'))
